Explain the difference between == and equals() in Java.
233
22-Jul-2024
Updated on 22-Jul-2024
Ashutosh Kumar Verma
22-Jul-2024Difference Between ‘==’ and equal()
“==” and “equals()” are used to compare objects, but they serve different purposes,
“==” (equality operator)
The
==
operator checks if the reference is equal. In other words, it checks whether two references refer to the same memory location, indicating that they do the same thing.For primitive data types (such as
int
,double
, etc.),==
ensures that values are equal.Example-
equals() method
The
equals()
method is a method defined in theObject
class to ensure value equality (and overridden in many classes such asString
andInteger
).By default,
equals()
of theObject
class behaves like==
(i.e., checks for reference equality). However, many classes overrideequals()
to compare contents or values of objects.Example-
In example above
equals()
compares the contents ofstr1
andstr2
(i.e. their character sequences), and since they are both "hello", it returns true.Key Differences
Purpose-
==
checks for reference equality or value equality for a primitive, whileequals()
is used to check content or value equality.Usage- Use
==
to check if two references point to the same object instance. Useequals()
to check if two objects are logically equivalent based on their internal state.Overriding- While
==
cannot be overridden (because it is an operator),equals()
can be overridden by classes to provide custom equality checks.==
Test whether two references point to the same thing.equals()
checks that two objects are logically equivalent based on their context or state, as defined by the class of theequals()
function.Also, Read: What is the significance of the 'final' keyword in Java?